<!--  -->
<template>
  <div id="playerBar">
    <div id="left">
      <img
        id="coverImg"
        :src="musicDetail.al ? musicDetail.al.picUrl : defalutImg"
        alt="封面"
      />
    </div>
    <div id="center">
      <div id="songInfo">
        <h1>{{ musicName }}</h1>
        <h2>{{ artistsName }}</h2>
      </div>
      <div id="control">
        <p id="curTime">{{ time(playInfo.curTime) }}</p>
        <div>
          <Slider
            ref="slider"
            :max="playInfo.maxTime"
            :value="playInfo.curTime"
            :tip-format="time"
            @mousedown.native="pauseTime"
            @mouseup.native="releaseTime"
            @on-change="drag"
          ></Slider>
        </div>
        <p id="maxTime">{{ time(playInfo.maxTime) }}</p>
      </div>
    </div>
    <div id="controlBtns">
      <img src="./svg/slow.svg" alt="减速" id="slow" @click="changeSpeed(-0.25)" />
      <img
        v-if="!playInfo.playing"
        src="./svg/play.svg"
        alt="播放"
        id="paly"
        @click="play"
      />
      <img
        v-if="playInfo.playing"
        src="./svg/pause.svg"
        alt="暂停"
        id="pause"
        @click="pause"
      />
      <img src="./svg/fast.svg" alt="加速" id="fast" @click="changeSpeed(0.25)" />
    </div>
    <div id="otherBtns">
      <img src="./svg/download.svg" alt="下载" @click="download" />
      <a
        ref="downloadA"
        href="#"
        :download="musicName + ' - ' + artistsName"
      ></a>
    </div>
    <!-- 隐藏的audio -->
    <audio
      ref="audio"
      @timeupdate="updateTime()"
      :src="musicDetail.url"
    ></audio>
  </div>
</template>

<script>
export default {
  data() {
    return {
      defalutImg:
        "https://img.alicdn.com/tps/TB1ld1GNFXXXXXLapXXXXXXXXXX-200-200.png",
      playInfo: {
        playing: false,
        curTime: 0,
        maxTime: 200,
        speed: 1,
      },
      isDragging: false,
      blobPath: "#",
      playable:true,  //这是播放锁，当歌曲发生错误时锁上，当重新初始化播放器（切换歌曲）时解锁
      musicDetail:{}
    }
  },

  props: {
    
  },

  components: {},

  computed: {
    //Audio原生的进度。
    currentTime() {
      return this.$$refs.audio.currentTime
    },
    musicName() {
      return this.musicDetail.name
        ? this.musicDetail.name
        : "歌名(超过最大长度会变成...)"
    },
    artistsName() {
      if (!this.musicDetail.ar) return "歌手名(超过最大长度会变成...)"
      //名字拼接
      let name = ""
      this.musicDetail.ar.forEach((item, index) => {
        name += item.name
        name += ","
      })
      //删除最后一个逗号
      name = name.substring(0, name.length - 1)
      return name
    },
  },

  mounted() {},

  methods: {
    // 61 => 01:01
    time(seconds) {
      let minutes = parseInt(seconds / 60)
      seconds = parseInt(seconds % 60)
      return (
        (minutes < 10 ? "0" + minutes : minutes) +
        ":" +
        (seconds < 10 ? "0" + seconds : seconds)
      )
    },
    //播放
    play() {
      //如果能够播放(原生audio没有出错)
      
      if(this.playable){
        console.log("播放")
      console.log(this.musicDetail.url)
        this.playInfo.playing = true
        console.log(this.$refs.audio)
        this.$refs.audio.play()
      }else{
        this.checkFee();
      }
    },
    //暂停
    pause() {
      this.playInfo.playing = false
      this.$refs.audio.pause()
    },
    //变速
    changeSpeed(n){
      //限速 0.25~2
      if(n>0 && this.$refs.audio.playbackRate==2) return;
      if(n<0 && this.$refs.audio.playbackRate==0.25) return;
      //真实变速
      this.$refs.audio.playbackRate+=n
      //提示当前速度
      this.$Message.destroy()
      this.$Message.info("X"+this.$refs.audio.playbackRate)
      console.log(this.$refs.audio.playbackRate)
    },
    //重新播放
    reload() {
      this.$refs.audio.reload()
    },
    //下载
    download() {
      console.log("下载")
      //开始loading动画
      const msg = this.$Message.loading('正在准备下载...', 0);
      let xhr = new XMLHttpRequest();
      let getURL=async function(self){
        let res = await self.axios
        .get(self.BaseURL+"/song/url?id="+self.musicDetail.id);
        return res.data.data[0].url
      }
      getURL(this).then(url=>{
        return this.axios.get(url,{
          responseType: 'blob'
        })
      }).then(res=>{
          console.log(res)
          console.log(typeof res);
          let fileBlob = res.data;
          let url=URL.createObjectURL(fileBlob);
          console.log(url)
          this.$refs.downloadA.href = url;
          this.$refs.downloadA.click();
          //关闭loading
          this.$Message.destroy()
      })
      // xhr.open("GET", url)
      // xhr.responseType = "blob"
      // xhr.send()
      // xhr.onload = () => {
      //   //blob格式的二进制数据
      //   const fileBlob = xhr.response
      //   //将blob转化成URL链接（其实可以将任意对象转成URL，实际上是生成资源映射路径）
      //   let urlImg = URL.createObjectURL(fileBlob)
      //   this.$refs.downloadA.href = urlImg
      //   console.log(this.$refs.downloadA)
      //   this.$refs.downloadA.click();
      // }
    },
    //更新播放条左边的进度时间
    updateTime() {
      this.playInfo.curTime = this.$refs.audio.currentTime
    },
    //拖拽时的处理
    drag(val) {
      this.$refs.audio.currentTime = val
      this.updateTime()
    },
    //在滑条按下鼠标
    pauseTime() {
      this.isDragging = true
    },
    //在滑条松开鼠标后
    releaseTime() {
      this.isDragging = false
    },
    checkFee(){
      if(this.musicDetail.fee==1){
        this.$Message.error("抱歉，VIP歌曲暂时无法播放")
      }else{
        this.$Message.error("对不起，暂时没有该曲的版权...")
      }
    },
    //播放器初始化：1.解锁播放，2.计算总时长，3.自动播放
    init(){
          this.playable = true;
          //歌曲切换了要更新playInfo的maxTime
          this.playInfo.maxTime=Math.floor(this.musicDetail.dt /1000);
          
          //歌曲切换最后要自动播放(因为数据变化后播放器需要时间进行重定向，F12 network可查看当前url状态码为302重定向，
          //如果不给重定向的时间直接播放，将报错" The element has no supported sources.")
          this.$nextTick(()=>this.play())
    }
  },
  mounted(){
    //因为只有当有音乐资源了，该组件才会加载，此时全局数据已经更新过，watch无法再次监听到，所以组件初始化时需要手动爬取一次全局数据
    this.musicDetail = this.$store.state.musicDetail;
    //同理，需要手动初始化播放器
    this.init();
    //给播放器增加权限检测机制
    this.$refs.audio.onerror=()=>{
      this.pause();
      this.playable = false;
      console.log("播放出错")
      if(this.musicDetail.fee==1){
        this.$Message.error("抱歉，VIP歌曲暂时无法播放")
      }else{
        this.$Message.error("对不起，暂时没有该曲的版权...")
      }
    }
    //播放器结束时要自动暂停
    this.$refs.audio.onended=()=>{
      this.pause();
    }
  },
  watch:{
    "$store.state.musicDetail":{
      handler(val,oldval){
        //更新局部musicDetail为全局vuex的musicDetail(局部和视图绑定)
          this.musicDetail = this.$store.state.musicDetail
          console.log(this.musicDetail)
          //1.初始化（从无到有） 2.歌曲变化
        if((!oldval.url) || val.url!=oldval.url){
          console.log("歌曲切换了"+oldval.url+"=>"+val.url)
          //重新初始化播放器
          this.init()
        }
      },
      deep:true
    }
  }
}
</script>
<style lang="scss" scoped>
@media screen and (min-width: 600px) {
  @import "./table.scss";
}
@media screen and (max-width: 600px) {
  @import "./phone.scss";
}
</style>
